﻿#include "mode_data.hpp"
#include <cstdarg>
#include "../../libcat/include/util/base.hpp"

#include <Windows.h>
#include <string>
#include <fstream>

using namespace std;

namespace {

    static std::map<std::string, sf::Texture> img_holder;

}

sf::Texture& ModeData::load_texture(std::string path)
{
    if (img_holder.find(path) == img_holder.end())
		while (!img_holder[path].loadFromFile(path)) {
			error_msg("Cannot find file %s", path);
			return img_holder[path];
		}
    img_holder[path].setSmooth(true);
    return img_holder[path];
}

sf::Texture& ModeData::load_texture2(std::string path)
{
    if (img_holder.find(path) == img_holder.end()) {
        img_holder[path].loadFromFile(path);
        img_holder[path].setSmooth(true);
    }
    return img_holder[path];
}

void ModeData::error_msg(const char* msg, ...)
{
    va_list args;
    char buf[256];
    va_start(args, msg);
    vsnprintf_s(buf, sizeof(buf), msg, args);
    blog(LOG_DEBUG, "[mode2_keyboard]%s", buf);
    va_end(args);
}
void ModeData::clear_holder()
{
	img_holder.clear();
}

char* ModeData::LoadFileAsBytes(const char* path)
{
#if _WIN64

	//fix open wchar file path
	int wchars_num = MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[wchars_num];
	MultiByteToWideChar(CP_UTF8, 0, path, -1, wstr, wchars_num);

	int size = 0;
	struct _stat64 statBuf;
	if (_wstat64(wstr, &statBuf) == 0)
	{
		size = statBuf.st_size;
	}
	else {
		size = 0;
	}
#else
	int wchars_num = MultiByteToWideChar(CP_UTF8, 0, path, -1, NULL, 0);
	wchar_t* wstr = new wchar_t[wchars_num];
	MultiByteToWideChar(CP_UTF8, 0, path, -1, wstr, wchars_num);

	int size = 0;
	struct _stat32 statBuf;
	if (_wstat32(wstr, &statBuf) == 0) {
		size = statBuf.st_size;
	}
	else {
		size = 0;
	}
#endif // X64
	std::fstream file;
	char* buf = (char*)malloc(size);

	file.open(wstr, std::ios::in | std::ios::binary);
	if (!file.is_open())
	{
		return NULL;
	}
	file.read(buf, size);
	file.close();
	delete wstr;
	return buf;
}